#include "gd32a508.h"

#include "systick.h"

#include "main.h"
#include "bsp.h"
#include "bsp_can.h"
#include "bsp_gpio.h"
#include "bsp_crc.h"
#include "bsp_adc.h"
#include "bsp_ads1110.h"
#include "bsp_usart.h"
#include "bsp_i2c.h"
#include "bsp_e2prom.h"

#include "app_sub_can.h"
#include "app_chg_can.h"
#include "app_main_can.h"
#include "app_dido.h"
#include "app_adc.h"
#include "app_ads1110.h"
#include "app_rs485.h"
#include "app_eeprom.h"


__IO uint32_t g_SysTickCount;
uint32_t g_SysHeartFlag;




static void init_bsp_object(void)
{
	init_bsp_can();
	init_bsp_dido();
	init_bsp_crc();
	init_bsp_adc();
	init_bsp_ads();
	init_dv_UART();
	init_dv_I2C();
	init_dv_E2PROM();

}
static void bsp_driver_init(void)
{
	dv_CAN.finit(EM_CAN_0,true);
	dv_CAN.finit(EM_CAN_1,true);
	dv_CAN.finit(EM_CAN_2,true);
	
	dv_DIDO.finit();
	dv_CRC32.finit();
	dv_ADC.finit();
	
	dv_UART.finit(9600);
	dv_I2C.finit(mI2_eep);
	dv_I2C.finit(mI2_ads1);
	dv_I2C.finit(mI2_ads2);
	dv_I2C.finit(mI2_ads3);
	dv_I2C.finit(mI2_ads4);

	dv_ADS.finit();
}
static void delay_poweroff(void)
{
	static uint16_t cnt = 0;
	// chg 与 on 检测信号为H电平时表示未接入外部信号
	if(subCan.txMes1.mes.in_chg == 1 && subCan.txMes1.mes.in_on == 1)
	{
		cnt++;
	}
	else
	{
		cnt=0;
	}
	
	if(cnt>=SYS_HEART_MS(2000))
	{
		dv_DIDO.fwrite(IO_PW,false);
	} 
}

static void app_state_init(void)
{
	app_dido_state_init();
	app_485_state_init();
	app_eep_state_init();	
}

static osTimeCost_T pTimecost2[3] = {0};

int main(void)
{
    uint8_t data[64] = {0,1,2,3,4,5,6,7,9,10,11};
	uint16_t TxCnt = 0;
    /* configure systick */
    systick_config();

	init_bsp_object();

	bsp_driver_init();

	delay_1ms(50);

	app_state_init();
	
	osTaskGetTimeCost(&pTimecost2[1]);

    while(1) 
	{	
		//dv_CAN.fcommunication_loop();

		app_dido_in_check();

		app_sub_can_rx_run();
		app_chg_can_rx_run();
		app_main_can_rx_run();

		app_dido_run();

		if(g_SysHeartFlag)
		{
			
			g_SysHeartFlag = false;
			osTaskGetTimeCost(&pTimecost2[0]);

			app_anlog_run();
			app_ads1110_run();
			app_485_run();
			app_eep_run();

			TxCnt++;
			
			if(TxCnt==SYS_HEART_MS(100))
			{
				app_sub_can_tx_run();
			}
			if(TxCnt==SYS_HEART_MS(110))
			{
				app_chg_can_tx_run();
			}
			if(TxCnt==SYS_HEART_MS(120))
			{
				app_main_can_tx_run();
				TxCnt = 0;
			}
			
			osTaskGetTimeCost(&pTimecost2[0]);

			if(pTimecost2[0].timeCostMs>=8)
			{
				dv_DIDO.LEDCtrl.State = 2;
			}
			osTaskGetTimeCost(&pTimecost2[1]);
			
			if(pTimecost2[1].timeCostMs>=20)
			{
				dv_DIDO.LEDCtrl.State = 3;
			}
			
			
			dv_DIDO.fledspark();
		}    
    }
}
